﻿using System.Diagnostics;
using System.Linq;
using System.Net;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;

namespace WorkerRole1
{
	using System.Threading;

	using Helpers;

	using Microsoft.WindowsAzure;
	using Microsoft.WindowsAzure.StorageClient;

	public class WorkerRole : RoleEntryPoint
	{
		public override void Run()
		{
			// This is a sample worker implementation. Replace with your logic.
			Trace.WriteLine("WorkerRole1 entry point called", "Information");

			CloudStorageAccount account = CloudStorageAccount.FromConfigurationSetting("StorageConnectionString");
			CloudQueueClient queueClient = account.CreateCloudQueueClient();
			CloudQueue queue = queueClient.GetQueueReference("myfirstqueue");

			queue.CreateIfNotExist ();

			while (true)
			{
				CloudQueueMessage message = queue.GetMessage ();
				//PopReceived (default 30 secondi)

				if (message != null)
				{
					MessageObject myObj = message.AsBytes.ToObjectFromoByteArray<MessageObject> ();
					
					//TODO: something

					queue.DeleteMessage ( message );
				}
				Thread.Sleep ( 10000 );
				Trace.WriteLine("Working", "Information");
			}
		}

		public override bool OnStart()
		{
			// Set the maximum number of concurrent connections 
			ServicePointManager.DefaultConnectionLimit = 12;

			DiagnosticMonitor.Start("DiagnosticsConnectionString");

			// For information on handling configuration changes
			// see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.
			RoleEnvironment.Changing += RoleEnvironmentChanging;

			CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) => configSetter(RoleEnvironment.GetConfigurationSettingValue(configName)));

			return base.OnStart();
		}

		private void RoleEnvironmentChanging(object sender, RoleEnvironmentChangingEventArgs e)
		{
			// If a configuration setting is changing
			if (e.Changes.Any(change => change is RoleEnvironmentConfigurationSettingChange))
			{
				// Set e.Cancel to true to restart this role instance
				e.Cancel = true;
			}
		}
	}
}
